package com.dxy.lc.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxy.lc.enums.RoomUserOpt;
import com.dxy.lc.listener.event.MemberEditEvent;
import com.dxy.lc.model.bean.MsgPayload;
import com.dxy.lc.model.entity.User;
import com.dxy.lc.service.MessageService;
import com.dxy.lc.service.SessionBindService;
import com.dxy.lc.service.UserService;
import com.dxy.lc.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class RoomEditEventListener {

    @Autowired
    private SessionBindService sessionBindService;
    @Autowired
    private UserService userService;
    @Autowired
    private MessageService messageService;

    @EventListener
    public void handleMemberEditEvent(MemberEditEvent event) {
        Integer roomId = event.getRoomId();
        Integer[] memberUserIds = event.getMemberUserIds();
        RoomUserOpt editType = event.getEditType();
        log.debug("handleRoomCreateEvent, roomId: {}, editType: {}, memberUserIds: {}", roomId, editType, JsonUtil.toJSON(memberUserIds));
        sessionBindService.bindSessionOnEditRoom(editType, roomId, memberUserIds);

        // 发送加群、退群消息
        List<User> ul = userService.list(new LambdaQueryWrapper<User>()
                .in(User::getId, memberUserIds));
        String usernames = ul.stream().map(User::getUsername).collect(Collectors.joining("、"));
        String content = usernames + (editType.equals(RoomUserOpt.JOIN) ? "加入群聊" : "退出群聊");
        MsgPayload data = new MsgPayload()
                .setRoomId(roomId)
                .setMsgType(0) // 属于系统消息
                .setContent(content)
                .setSimpleText(content)
                .setSentAt(LocalDateTimeUtil.format(LocalDateTime.now(),"yyyy-MM-dd'T'HH:mm:ss"));
        messageService.saveAndSendMsg(data);
    }
}
